"""
股票量化分析系统 V2.0 - 增强版Web界面
新增功能：
1. 数据导出（Excel）
2. 多股票对比分析
3. 可配置参数
4. 模块化设计
"""

import streamlit as st

# 页面配置必须在最前面，在导入其他模块之前
st.set_page_config(
    page_title="智能股票量化分析系统 V2.0",
    page_icon="📈",
    layout="wide",
    initial_sidebar_state="expanded"
)

# 现在导入其他模块
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import pandas as pd
from datetime import datetime
import traceback
import sys
import logging

# 导入重构后的模块（V2.2.1 - 含智能交易日判断）
from core import StockDataFetcher, TechnicalIndicators, QuantitativeAnalyzer, RiskAnalyzer
from utils import DataExporter, MultiStockAnalyzer, MAAnalyzer, ChipAnalyzer

# 回测系统导入 V2.4.0
from backtest import BacktestEngine
from backtest.visualization import BacktestVisualizer
from strategies import MAStrategy, BreakoutStrategy, RSIStrategy, MACDStrategy
# 注意：backtest_page 改为从 ui_components 导入（避免 Streamlit 自动导航）
try:
    from ui_components.backtest_page import backtest_page
except ImportError:
    from pages.backtest_page import backtest_page
from utils.visualization import (
    create_candlestick_chart,
    create_indicator_dashboard,
    display_realtime_info,
    display_analysis_result,
    create_chip_distribution_chart,
    display_ma_analysis,
    display_ma_cross,
    display_ma_support_resistance,
    display_chip_analysis,
    display_trading_decision
)
from config import current_config as config

# 配置日志
logging.basicConfig(
    level=getattr(logging, config.LOG_LEVEL),
    format=config.LOG_FORMAT,
    datefmt=config.LOG_DATE_FORMAT
)

# ========== 自定义CSS + 中文界面优化 ========== ✨
st.markdown("""
    <style>
    /* 导入专业中文字体 */
    @import url('https://fonts.googleapis.com/css2?family=Noto+Sans+SC:wght@300;400;500;700&display=swap');
    
    /* 全局中文字体设置 */
    html, body, [class*="css"], input, textarea, select, button {
        font-family: 'Noto Sans SC', 'Microsoft YaHei', 'SimHei', sans-serif !important;
    }
    
    /* 优化中文字符渲染 */
    * {
        -webkit-font-smoothing: antialiased;
        -moz-osx-font-smoothing: grayscale;
        text-rendering: optimizeLegibility;
    }
    
    /* 主背景 - 清爽浅绿色 */
    .main {
        background: linear-gradient(135deg, #ffffff 0%, #f0fdf4 100%);
    }
    
    /* 侧边栏优化 - 清爽绿色 */
    [data-testid="stSidebar"] {
        background: linear-gradient(180deg, #10b981 0%, #059669 100%);
        color: white;
    }
    
    /* 侧边栏标签和标题为白色 */
    [data-testid="stSidebar"] label,
    [data-testid="stSidebar"] h1,
    [data-testid="stSidebar"] h2,
    [data-testid="stSidebar"] h3,
    [data-testid="stSidebar"] p,
    [data-testid="stSidebar"] span:not(input):not(input *) {
        color: white !important;
    }
    
    /* 侧边栏输入框文字颜色 - 纯黑色，最高优先级 */
    [data-testid="stSidebar"] input,
    [data-testid="stSidebar"] textarea,
    [data-testid="stSidebar"] .stTextInput input,
    [data-testid="stSidebar"] .stNumberInput input,
    [data-testid="stSidebar"] .stTextArea textarea,
    [data-testid="stSidebar"] .stSelectbox input,
    [data-testid="stSidebar"] [data-baseweb="input"] input,
    [data-testid="stSidebar"] [role="spinbutton"] {
        color: #000000 !important;
        background-color: #ffffff !important;
        -webkit-text-fill-color: #000000 !important;
    }
    
    /* 侧边栏选择框下拉选项 */
    [data-testid="stSidebar"] [data-baseweb="select"] div,
    [data-testid="stSidebar"] .stSelectbox div {
        color: #000000 !important;
    }
    
    /* 隐藏自动生成的页面导航 */
    [data-testid="stSidebarNav"] {
        display: none !important;
    }
    
    section[data-testid="stSidebarNav"] {
        display: none !important;
    }
    
    /* 隐藏页面链接 */
    [data-testid="stSidebar"] ul {
        display: none !important;
    }
    
    [data-testid="stSidebar"] li {
        display: none !important;
    }
    
    /* 只显示我们自定义的内容 */
    [data-testid="stSidebar"] > div:first-child > div:first-child {
        display: none !important;
    }
    
    [data-testid="stSidebar"] .stRadio > label {
        color: white !important;
        font-weight: 500;
    }
    
    /* 侧边栏按钮样式 - 清爽风格 */
    [data-testid="stSidebar"] .stButton > button {
        background: rgba(255, 255, 255, 0.25) !important;
        color: white !important;
        border: 2px solid rgba(255, 255, 255, 0.4) !important;
        font-weight: 700 !important;
        letter-spacing: 0.8px;
        backdrop-filter: blur(10px);
        text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.3);
    }
    
    [data-testid="stSidebar"] .stButton > button:hover {
        background: rgba(255, 255, 255, 0.35) !important;
        border-color: rgba(255, 255, 255, 0.6) !important;
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.25);
    }
    
    [data-testid="stSidebar"] .stButton > button[kind="primary"] {
        background: rgba(255, 255, 255, 0.95) !important;
        color: #0c4a6e !important;
        border: none !important;
        font-weight: 800 !important;
        text-shadow: none;
    }
    
    [data-testid="stSidebar"] .stButton > button[kind="primary"]:hover {
        background: white !important;
        color: #0284c7 !important;
    }
    
    /* 卡片容器样式 */
    .element-container {
        margin-bottom: 1rem;
    }
    
    /* 指标卡片样式 - 清爽绿色设计 */
    .stMetric {
        background: linear-gradient(135deg, #ffffff 0%, #f0fdf4 100%);
        padding: 20px;
        border-radius: 12px;
        box-shadow: 0 2px 8px rgba(16, 185, 129, 0.1);
        border: 1.5px solid rgba(209, 250, 229, 0.8);
        transition: all 0.3s ease;
    }
    
    .stMetric:hover {
        box-shadow: 0 4px 16px rgba(16, 185, 129, 0.2);
        transform: translateY(-2px);
        border-color: rgba(167, 243, 208, 1);
    }
    
    .stMetric label {
        font-size: 13px !important;
        font-weight: 600 !important;
        color: #047857 !important;
        text-transform: uppercase;
        letter-spacing: 0.5px;
    }
    
    .stMetric [data-testid="stMetricValue"] {
        font-size: 26px !important;
        font-weight: 700 !important;
        color: #065f46 !important;
    }
    
    /* 标题优化 - 清爽绿色 */
    h1 {
        background: linear-gradient(135deg, #10b981 0%, #059669 100%);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
        background-clip: text;
        font-weight: 700 !important;
        font-size: 2.5rem !important;
        margin-bottom: 1.5rem !important;
    }
    
    h2 {
        color: #065f46 !important;
        font-weight: 600 !important;
        font-size: 1.8rem !important;
        margin-top: 2rem !important;
        margin-bottom: 1rem !important;
    }
    
    h3 {
        color: #047857 !important;
        font-weight: 600 !important;
        font-size: 1.3rem !important;
    }
    
    /* 按钮优化 - 清爽绿色 */
    .stButton > button {
        background: linear-gradient(135deg, #d1fae5 0%, #a7f3d0 100%);
        color: #065f46 !important;
        font-weight: 700 !important;
        font-size: 15px !important;
        padding: 0.9rem 1rem !important;
        border-radius: 10px !important;
        border: 1.5px solid #6ee7b7 !important;
        letter-spacing: 0.5px;
        transition: all 0.3s ease;
        box-shadow: 0 2px 8px rgba(16, 185, 129, 0.15);
        min-height: 80px !important;
        line-height: 1.5 !important;
        white-space: pre-line !important;
    }
    
    .stButton > button:hover {
        background: linear-gradient(135deg, #a7f3d0 0%, #6ee7b7 100%);
        transform: translateY(-1px);
        box-shadow: 0 4px 12px rgba(16, 185, 129, 0.25);
        border-color: #10b981 !important;
    }
    
    /* 侧边栏功能按钮 - 统一绿色背景 */
    /* 选中状态 (Primary) - 红色粗边框区分 */
    [data-testid="stSidebar"] .stButton > button[kind="primary"],
    .stButton > button[kind="primary"] {
        background: linear-gradient(135deg, #d1fae5 0%, #a7f3d0 100%) !important;
        color: #065f46 !important;
        border: 3px solid #ef4444 !important;
        box-shadow: 0 3px 10px rgba(239, 68, 68, 0.3) !important;
        font-weight: 800 !important;
    }
    
    [data-testid="stSidebar"] .stButton > button[kind="primary"]:hover,
    .stButton > button[kind="primary"]:hover {
        background: linear-gradient(135deg, #d1fae5 0%, #a7f3d0 100%) !important;
        border-color: #dc2626 !important;
        box-shadow: 0 5px 15px rgba(239, 68, 68, 0.4) !important;
        transform: translateY(-1px);
    }
    
    /* 未选中状态 (Secondary) - 相同背景色，细灰边框区分 */
    [data-testid="stSidebar"] .stButton > button[kind="secondary"],
    .stButton > button[kind="secondary"] {
        background: linear-gradient(135deg, #d1fae5 0%, #a7f3d0 100%) !important;
        color: #065f46 !important;
        border: 1.5px solid #94a3b8 !important;
        box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1) !important;
        font-weight: 600 !important;
    }
    
    [data-testid="stSidebar"] .stButton > button[kind="secondary"]:hover,
    .stButton > button[kind="secondary"]:hover {
        background: linear-gradient(135deg, #d1fae5 0%, #a7f3d0 100%) !important;
        border-color: #64748b !important;
        color: #065f46 !important;
        box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15) !important;
        transform: translateY(-1px);
    }
    
    /* 隐藏标记div */
    .analyze-btn-container {
        display: none;
    }
    
    
    /* 输入框优化 - 修复字体颜色 */
    .stTextInput > div > div > input,
    .stTextArea > div > div > textarea {
        background-color: #ffffff !important;
        color: #000000 !important;
        border-radius: 12px !important;
        border: 2px solid #e2e8f0 !important;
        padding: 12px 16px !important;
        font-size: 15px !important;
        font-weight: 500 !important;
        transition: all 0.3s ease;
    }
    
    .stTextInput > div > div > input:focus,
    .stTextArea > div > div > textarea:focus {
        border-color: #10b981 !important;
        box-shadow: 0 0 0 3px rgba(16, 185, 129, 0.15) !important;
        background-color: #ffffff !important;
    }
    
    /* 输入框占位符颜色 */
    .stTextInput > div > div > input::placeholder,
    .stTextArea > div > div > textarea::placeholder {
        color: #94a3b8 !important;
        opacity: 1 !important;
    }
    
    /* 选择框优化 */
    .stSelectbox > div > div {
        background-color: #ffffff !important;
        border-radius: 12px !important;
        border: 2px solid #e2e8f0 !important;
    }
    
    .stSelectbox > div > div > div {
        color: #000000 !important;
        font-weight: 500 !important;
    }
    
    /* 下拉选项颜色 */
    [data-baseweb="select"] > div {
        background-color: #ffffff !important;
        color: #000000 !important;
    }
    
    /* 滑块优化 - 绿色主题 */
    .stSlider > div > div > div {
        background: linear-gradient(90deg, #10b981 0%, #059669 100%);
    }
    
    .stSlider > div > div > div > div {
        background-color: #10b981 !important;
    }
    
    /* 数据表格优化 */
    .stDataFrame {
        border-radius: 12px !important;
        overflow: hidden;
        box-shadow: 0 4px 12px rgba(0,0,0,0.08) !important;
        border: 1px solid #e2e8f0 !important;
    }
    
    /* 信息提示框优化 */
    .stAlert {
        border-radius: 12px !important;
        border-left: 4px solid !important;
        padding: 1rem 1.5rem !important;
        box-shadow: 0 2px 8px rgba(0,0,0,0.05);
    }
    
    /* 成功提示 */
    .stSuccess {
        background-color: #f0fdf4 !important;
        border-left-color: #10b981 !important;
        color: #065f46 !important;
    }
    
    /* 信息提示 - 绿色主题 */
    .stInfo {
        background-color: #f0fdf4 !important;
        border-left-color: #10b981 !important;
        color: #065f46 !important;
    }
    
    /* 警告提示 */
    .stWarning {
        background-color: #fffbeb !important;
        border-left-color: #f59e0b !important;
        color: #92400e !important;
    }
    
    /* 错误提示 */
    .stError {
        background-color: #fef2f2 !important;
        border-left-color: #ef4444 !important;
        color: #991b1b !important;
    }
    
    /* 展开面板优化 - 绿色主题 */
    .streamlit-expanderHeader {
        background: linear-gradient(135deg, #f0fdf4 0%, #d1fae5 100%);
        border-radius: 12px !important;
        padding: 1rem 1.5rem !important;
        font-weight: 600 !important;
        font-size: 16px !important;
        color: #047857 !important;
        border: 1.5px solid #a7f3d0;
        transition: all 0.3s ease;
    }
    
    .streamlit-expanderHeader:hover {
        background: linear-gradient(135deg, #d1fae5 0%, #a7f3d0 100%);
        box-shadow: 0 2px 8px rgba(16, 185, 129, 0.15);
        border-color: #6ee7b7;
    }
    
    /* 标签页优化 */
    .stTabs [data-baseweb="tab-list"] {
        gap: 12px;
        background-color: transparent;
    }
    
    .stTabs [data-baseweb="tab"] {
        background: white;
        border-radius: 12px 12px 0 0;
        padding: 12px 24px !important;
        font-weight: 600 !important;
        border: 1px solid #e2e8f0;
        border-bottom: none;
        transition: all 0.3s ease;
    }
    
    .stTabs [data-baseweb="tab"]:hover {
        background: #f8fafc;
    }
    
    .stTabs [data-baseweb="tab"][aria-selected="true"] {
        background: linear-gradient(135deg, #10b981 0%, #059669 100%);
        color: white !important;
        border-color: #10b981;
    }
    
    /* 分隔线优化 */
    hr {
        margin: 2rem 0;
        border: none;
        height: 2px;
        background: linear-gradient(90deg, transparent 0%, #e2e8f0 50%, transparent 100%);
    }
    
    /* 右上角菜单优化 */
    [data-testid="stToolbar"] {
        opacity: 0.3;
        transition: opacity 0.3s ease;
    }
    
    [data-testid="stToolbar"]:hover {
        opacity: 1;
    }
    
    /* 图表容器优化 */
    [data-testid="stPlotlyChart"] {
        background: white;
        border-radius: 16px;
        padding: 1rem;
        box-shadow: 0 4px 12px rgba(0,0,0,0.08);
        border: 1px solid #e2e8f0;
    }
    
    /* Spinner优化 */
    .stSpinner > div {
        border-color: #3b82f6 !important;
    }
    
    /* 下载按钮优化 */
    .stDownloadButton > button {
        background: linear-gradient(135deg, #8b5cf6 0%, #7c3aed 100%) !important;
        box-shadow: 0 4px 12px rgba(139, 92, 246, 0.3);
    }
    
    .stDownloadButton > button:hover {
        background: linear-gradient(135deg, #7c3aed 0%, #6d28d9 100%) !important;
        box-shadow: 0 6px 16px rgba(139, 92, 246, 0.4);
    }
    
    /* 滚动条优化 */
    ::-webkit-scrollbar {
        width: 10px;
        height: 10px;
    }
    
    ::-webkit-scrollbar-track {
        background: #f1f5f9;
        border-radius: 10px;
    }
    
    ::-webkit-scrollbar-thumb {
        background: linear-gradient(180deg, #cbd5e1 0%, #94a3b8 100%);
        border-radius: 10px;
    }
    
    ::-webkit-scrollbar-thumb:hover {
        background: linear-gradient(180deg, #94a3b8 0%, #64748b 100%);
    }
    </style>
    
    <script>
    // 强制设置侧边栏输入框文字为黑色
    function fixSidebarInputs() {
        // 获取侧边栏
        const sidebar = document.querySelector('[data-testid="stSidebar"]');
        if (!sidebar) return;
        
        // 选择所有输入元素
        const inputs = sidebar.querySelectorAll('input, textarea');
        inputs.forEach(function(input) {
            input.style.setProperty('color', '#000000', 'important');
            input.style.setProperty('background-color', '#ffffff', 'important');
            input.style.setProperty('-webkit-text-fill-color', '#000000', 'important');
        });
        
        // 选择框的div
        const selectDivs = sidebar.querySelectorAll('[data-baseweb="select"] div, .stSelectbox div');
        selectDivs.forEach(function(div) {
            if (div.querySelector('input')) return; // 跳过包含input的div
            div.style.setProperty('color', '#000000', 'important');
        });
    }
    
    // 设置按钮样式
    function setButtonStyles() {
        const buttons = document.querySelectorAll('button');
        buttons.forEach(function(btn) {
            const text = btn.textContent;
            
            // 分析按钮 - 浅红色
            if (text.includes('🚀 开始分析')) {
                btn.style.setProperty('background', 'linear-gradient(135deg, #fee2e2 0%, #fecaca 100%)', 'important');
                btn.style.setProperty('color', '#991b1b', 'important');
                btn.style.setProperty('border', '1.5px solid #fca5a5', 'important');
                btn.style.setProperty('font-weight', '700', 'important');
                
                btn.addEventListener('mouseenter', function() {
                    this.style.setProperty('background', 'linear-gradient(135deg, #fecaca 0%, #fca5a5 100%)', 'important');
                    this.style.setProperty('border-color', '#f87171', 'important');
                    this.style.setProperty('color', '#7f1d1d', 'important');
                    this.style.setProperty('box-shadow', '0 4px 12px rgba(239, 68, 68, 0.3)', 'important');
                });
                
                btn.addEventListener('mouseleave', function() {
                    this.style.setProperty('background', 'linear-gradient(135deg, #fee2e2 0%, #fecaca 100%)', 'important');
                    this.style.setProperty('border-color', '#fca5a5', 'important');
                    this.style.setProperty('color', '#991b1b', 'important');
                    this.style.setProperty('box-shadow', '', 'important');
                });
            }
            
            // 功能选择按钮 - 检查kind属性
            const kind = btn.getAttribute('kind');
            
            // Primary按钮 (选中状态) - 统一浅绿背景 + 红色粗边框
            if (kind === 'primary' && (text.includes('单股票') || text.includes('多股票') || text.includes('打板') || text.includes('策略') || text.includes('系统'))) {
                btn.style.setProperty('background', 'linear-gradient(135deg, #d1fae5 0%, #a7f3d0 100%)', 'important');
                btn.style.setProperty('color', '#065f46', 'important');
                btn.style.setProperty('border', '3px solid #ef4444', 'important');
                btn.style.setProperty('font-weight', '800', 'important');
            }
            
            // Secondary按钮 (未选中状态) - 统一浅绿背景 + 细灰边框
            if (kind === 'secondary' && (text.includes('单股票') || text.includes('多股票') || text.includes('打板') || text.includes('策略') || text.includes('系统'))) {
                btn.style.setProperty('background', 'linear-gradient(135deg, #d1fae5 0%, #a7f3d0 100%)', 'important');
                btn.style.setProperty('color', '#065f46', 'important');
                btn.style.setProperty('border', '1.5px solid #94a3b8', 'important');
                btn.style.setProperty('font-weight', '600', 'important');
            }
        });
    }
    
    // 应用所有样式
    function applyAllStyles() {
        setButtonStyles();
        fixSidebarInputs();
    }
    
    // 初始设置
    setTimeout(applyAllStyles, 100);
    setTimeout(fixSidebarInputs, 200);  // 再次执行确保生效
    setTimeout(fixSidebarInputs, 500);  // 第三次确保
    
    // 监听DOM变化，重新应用样式
    const observer = new MutationObserver(applyAllStyles);
    observer.observe(document.body, { childList: true, subtree: true });
    
    // 监听输入事件，确保输入时文字也是黑色
    document.addEventListener('input', function(e) {
        if (e.target.tagName === 'INPUT' || e.target.tagName === 'TEXTAREA') {
            const sidebar = document.querySelector('[data-testid="stSidebar"]');
            if (sidebar && sidebar.contains(e.target)) {
                e.target.style.setProperty('color', '#000000', 'important');
                e.target.style.setProperty('-webkit-text-fill-color', '#000000', 'important');
            }
        }
    }, true);
    </script>
""", unsafe_allow_html=True)


def main():
    """主函数"""
    
    # 侧边栏
    with st.sidebar:
        # 移除图标，直接显示标题
        st.markdown("""
        <h1 style='color: white; 
                   font-size: 28px; 
                   font-weight: 800; 
                   text-align: center;
                   text-shadow: 3px 3px 6px rgba(0,0,0,0.5);
                   margin-top: 20px;
                   margin-bottom: 20px;
                   letter-spacing: 1px;
                   background: rgba(255, 255, 255, 0.1);
                   padding: 15px;
                   border-radius: 10px;
                   border: 2px solid rgba(255, 255, 255, 0.3);'>
            📈 智能量化分析 V3.0.0
        </h1>
        """, unsafe_allow_html=True)
        st.markdown("---")
        
        # 显示交易状态 ✨ NEW
        from utils import TradingCalendar
        status = TradingCalendar.get_trading_status()
        
        with st.expander("📅 交易日历", expanded=False):
            st.write(f"**今日日期:** {status['今日日期']}")
            st.write(f"**是否交易日:** {'✅ 是' if status['是否交易日'] else '⚠️ 否'}")
            st.write(f"**市场状态:** {status['市场状态']}")
            if not status['是否交易日'] or not status['是否交易时间']:
                st.info(f"💡 将使用 {status['最近交易日']} 的数据")
        
        st.markdown("---")
        
        # 功能选择 - 网格布局（一排两个）
        st.markdown("### 📌 选择功能")
        
        # 初始化模式
        if 'mode' not in st.session_state:
            st.session_state.mode = "单股票分析"
        
        # 第一行：单股票分析、多股票对比
        col1, col2 = st.columns(2)
        with col1:
            if st.button("📊\n\n单股票\n分析", 
                        use_container_width=True,
                        type="primary" if st.session_state.mode == "单股票分析" else "secondary",
                        key="btn_single"):
                st.session_state.mode = "单股票分析"
        
        with col2:
            if st.button("📉\n\n多股票\n对比", 
                        use_container_width=True,
                        type="primary" if st.session_state.mode == "多股票对比" else "secondary",
                        key="btn_multi"):
                st.session_state.mode = "多股票对比"
        
        # 第二行：打板监控、策略回测
        col3, col4 = st.columns(2)
        with col3:
            if st.button("📍\n\n打板\n监控", 
                        use_container_width=True,
                        type="primary" if st.session_state.mode == "打板监控" else "secondary",
                        key="btn_limitup"):
                st.session_state.mode = "打板监控"
        
        with col4:
            if st.button("📈\n\n策略\n回测", 
                        use_container_width=True,
                        type="primary" if st.session_state.mode == "策略回测" else "secondary",
                        key="btn_backtest"):
                st.session_state.mode = "策略回测"
        
        # 第三行：系统配置
        col5, col6 = st.columns(2)
        with col5:
            if st.button("⚙️\n\n系统\n配置", 
                        use_container_width=True,
                        type="primary" if st.session_state.mode == "系统配置" else "secondary",
                        key="btn_config"):
                st.session_state.mode = "系统配置"
        
        mode = st.session_state.mode
        
        st.markdown("---")
        
        if mode == "单股票分析":
            # 单股票分析模式
            stock_input = st.text_input(
                "输入股票代码或名称",
                placeholder="例如: 600519 或 贵州茅台",
                help="支持6位股票代码或股票名称"
            )
            
            period = st.selectbox("K线周期", ["日K", "周K", "月K"], index=0)
            period_map = {"日K": "daily", "周K": "weekly", "月K": "monthly"}
            
            days = st.slider("历史数据天数", 30, 730, config.DEFAULT_HISTORY_DAYS)
            
            # 添加分析按钮的特殊标记
            st.markdown('<div class="analyze-btn-container">', unsafe_allow_html=True)
            analyze_btn = st.button("🚀 开始分析", key="analyze_button", use_container_width=True)
            st.markdown('</div>', unsafe_allow_html=True)
            
            # 导出选项
            if st.session_state.get('analysis_complete', False):
                st.markdown("---")
                st.markdown("### 📥 数据导出")
                if st.button("📊 导出分析报告", use_container_width=True):
                    export_report()
        
        elif mode == "策略回测":
            # 策略回测模式
            st.markdown("### 🎯 策略回测")
            
            stock_input = st.text_input(
                "输入股票代码或名称",
                placeholder="例如: 600519 或 贵州茅台",
                key="backtest_stock",
                help="支持6位股票代码或股票名称"
            )
            
            # 选择策略
            strategy_name = st.selectbox(
                "选择策略",
                ["均线交叉策略", "突破策略", "RSI策略", "MACD策略"]
            )
            
            # 策略参数设置
            with st.expander("⚙️ 策略参数设置", expanded=True):
                if strategy_name == "均线交叉策略":
                    ma_short = st.slider("短期均线", 3, 20, 5)
                    ma_long = st.slider("长期均线", 10, 60, 20)
                elif strategy_name == "突破策略":
                    period = st.slider("突破周期", 5, 60, 20)
                elif strategy_name == "RSI策略":
                    rsi_period = st.slider("RSI周期", 6, 28, 14)
                    oversold = st.slider("超卖阈值", 10, 40, 30)
                    overbought = st.slider("超买阈值", 60, 90, 70)
                elif strategy_name == "MACD策略":
                    fast = st.slider("快线", 6, 20, 12)
                    slow = st.slider("慢线", 20, 35, 26)
                    signal = st.slider("信号线", 5, 15, 9)
            
            # 回测参数
            with st.expander("💰 回测参数设置", expanded=True):
                initial_capital = st.number_input("初始资金", 10000, 10000000, 100000, step=10000)
                days = st.slider("回测天数", 60, 730, 250)
                commission = st.number_input("手续费率", 0.0001, 0.01, 0.0003, step=0.0001, format="%.4f")
                slippage = st.number_input("滑点比例", 0.0, 0.01, 0.001, step=0.001, format="%.3f")
            
            backtest_btn = st.button("🚀 开始回测", type="primary", use_container_width=True)
        
        elif mode == "多股票对比":
            # 多股票对比模式
            st.markdown("### 多股票对比分析")
            
            stock_codes_input = st.text_area(
                "输入股票代码（每行一个）",
                placeholder="600519\n000858\n600036",
                height=150
            )
            
            days = st.slider("历史数据天数", 30, 365, 65, key="multi_days")
            
            compare_btn = st.button("🔍 开始对比", type="primary", use_container_width=True)
        
        else:
            # 系统配置模式
            st.markdown("### ⚙️ 系统配置")
            
            st.number_input("请求重试次数", 1, 5, config.REQUEST_RETRY, key="retry")
            st.number_input("请求超时(秒)", 10, 60, config.REQUEST_TIMEOUT, key="timeout")
            
            st.markdown("---")
            st.info("配置功能开发中...")
    
    # 主页面
    if mode == "单股票分析":
        single_stock_analysis(stock_input if 'stock_input' in locals() else "",
                             analyze_btn if 'analyze_btn' in locals() else False,
                             period_map[period] if 'period' in locals() else 'daily',
                             days if 'days' in locals() else 250)
    
    elif mode == "策略回测":
        # 准备策略参数
        strategy_params = {}
        if 'strategy_name' in locals():
            if strategy_name == "均线交叉策略":
                strategy_params = {'ma_short': ma_short, 'ma_long': ma_long}
            elif strategy_name == "突破策略":
                strategy_params = {'period': period}
            elif strategy_name == "RSI策略":
                strategy_params = {'period': rsi_period, 'oversold': oversold, 'overbought': overbought}
            elif strategy_name == "MACD策略":
                strategy_params = {'fast_period': fast, 'slow_period': slow, 'signal_period': signal}
        
        backtest_page(
            stock_input if 'stock_input' in locals() else "",
            strategy_name if 'strategy_name' in locals() else "均线交叉策略",
            strategy_params,
            initial_capital if 'initial_capital' in locals() else 100000,
            days if 'days' in locals() else 250,
            commission if 'commission' in locals() else 0.0003,
            slippage if 'slippage' in locals() else 0.001,
            backtest_btn if 'backtest_btn' in locals() else False
        )
    
    elif mode == "多股票对比":
        multi_stock_comparison(stock_codes_input if 'stock_codes_input' in locals() else "",
                              compare_btn if 'compare_btn' in locals() else False,
                              days if 'days' in locals() else 65)
    
    elif mode == "打板监控":
        # 打板监控页面
        try:
            from pages.limit_up_page import limit_up_monitoring_page
            limit_up_monitoring_page()
        except ImportError:
            try:
                from ui_components.limit_up_page import limit_up_monitoring_page
                limit_up_monitoring_page()
            except ImportError:
                st.error("❌ 打板监控模块加载失败")
    
    else:
        system_config_page()


def single_stock_analysis(stock_input, analyze_btn, period, days):
    """单股票分析页面"""
    st.markdown("# 📊 单股票分析")
    st.markdown("#### 基于多维度技术指标的专业量化分析")
    st.markdown("---")
    
    if not stock_input:
        show_welcome_page()
        return
    
    if analyze_btn:
        perform_single_analysis(stock_input, period, days)


def perform_single_analysis(stock_input, period, days):
    """执行单股票分析"""
    with st.spinner("🔍 正在获取数据并分析..."):
        try:
            fetcher = StockDataFetcher()
            
            st.info(f"🔍 正在查找股票: {stock_input}")
            stock_code = fetcher.get_stock_code(stock_input)
            
            if not stock_code:
                st.error(f"❌ 未找到股票: {stock_input}")
                return
            
            st.success(f"✅ 找到股票代码: {stock_code}")
            
            # 获取数据
            st.info("📊 正在获取实时行情...")
            realtime_data = fetcher.get_realtime_data(stock_code)
            
            if realtime_data:
                st.success("✅ 实时数据获取成功")
            else:
                st.warning("⚠️ 实时数据获取失败")
            
            st.info(f"📈 正在获取历史K线数据...")
            hist_data = fetcher.get_historical_data(stock_code, period=period, days=days)
            
            if hist_data is None or len(hist_data) == 0:
                st.error("❌ 无法获取历史数据")
                return
            
            st.success(f"✅ 历史数据获取成功: {len(hist_data)} 条记录")
            
            # 计算技术指标
            hist_data = TechnicalIndicators.calculate_all_indicators(hist_data)
            
            # 获取股票名称
            stock_name = realtime_data['股票名称'] if realtime_data else f"股票 {stock_code}"
            
            # 显示分析结果
            if realtime_data:
                display_realtime_info(realtime_data)
            else:
                st.title(f"{stock_name} ({stock_code})")
                st.warning("⚠️ 实时数据获取失败，以下为历史数据分析")
            
            st.markdown("---")
            
            # 技术指标仪表盘
            create_indicator_dashboard(hist_data)
            
            st.markdown("---")
            
            # ========== 均线系统分析 ========== ✨ NEW
            ma_arrangement = MAAnalyzer.analyze_ma_arrangement(hist_data)
            ma_cross = MAAnalyzer.analyze_ma_cross(hist_data)
            ma_support_resistance = MAAnalyzer.analyze_ma_support_resistance(hist_data)
            
            display_ma_analysis(ma_arrangement)
            
            col1, col2 = st.columns(2)
            with col1:
                display_ma_cross(ma_cross)
            with col2:
                display_ma_support_resistance(ma_support_resistance)
            
            st.markdown("---")
            
            # ========== 筹码峰分析 ========== ✨ NEW
            chip_dist = ChipAnalyzer.calculate_chip_distribution(hist_data, lookback_days=90)
            chip_conc = ChipAnalyzer.calculate_chip_concentration(hist_data)
            chip_mig = ChipAnalyzer.analyze_chip_migration(hist_data)
            
            display_chip_analysis(chip_dist, chip_conc, chip_mig)
            
            # 筹码分布图
            st.markdown("#### 📊 筹码分布可视化")
            chip_chart = create_chip_distribution_chart(hist_data, lookback_days=90)
            if chip_chart:
                st.plotly_chart(chip_chart, use_container_width=True)
            
            st.markdown("---")
            
            # ========== 交易决策分析 ========== ✨ NEW V2.3
            from utils import TradingAdvisor
            
            st.info("💡 正在生成交易决策建议...")
            advisor = TradingAdvisor(realtime_data, hist_data)
            trading_plan = advisor.comprehensive_trading_plan()
            
            if trading_plan:
                display_trading_decision(trading_plan)
            
            st.markdown("---")
            
            # 增强分析
            from utils.enhanced_analysis import EnhancedAnalyzer
            
            # 量价关系分析
            st.subheader("📊 其他深度分析")
            col1, col2 = st.columns(2)
            
            with col1:
                volume_price = EnhancedAnalyzer.analyze_volume_price_relation(hist_data)
                if volume_price:
                    st.markdown("#### 💹 量价关系")
                    for key, value in volume_price.items():
                        st.write(f"**{key}:** {value}")
                
                st.markdown("---")
                
                # 支撑压力位
                support_resistance = EnhancedAnalyzer.analyze_support_resistance(hist_data)
                if support_resistance:
                    st.markdown("#### 🎯 支撑压力位")
                    for key, value in support_resistance.items():
                        st.write(f"**{key}:** {value}")
            
            with col2:
                # 趋势强度
                trend_strength = EnhancedAnalyzer.analyze_trend_strength(hist_data)
                if trend_strength:
                    st.markdown("#### 📈 趋势强度")
                    for key, value in trend_strength.items():
                        st.write(f"**{key}:** {value}")
                
                st.markdown("---")
                
                # 动量分析
                momentum = EnhancedAnalyzer.analyze_momentum(hist_data)
                if momentum:
                    st.markdown("#### ⚡ 动量分析")
                    for key, value in momentum.items():
                        st.write(f"**{key}:** {value}")
            
            st.markdown("---")
            
            # 筹码分布
            chip_dist = EnhancedAnalyzer.analyze_chip_distribution(hist_data)
            if chip_dist:
                st.subheader("💎 筹码分布分析")
                cols = st.columns(len(chip_dist))
                for i, (key, value) in enumerate(chip_dist.items()):
                    with cols[i]:
                        st.metric(key, value)
            
            st.markdown("---")
            
            # 量化分析（原有+增强+均线+筹码）
            analyzer = QuantitativeAnalyzer(realtime_data, hist_data)
            signals, score = analyzer.comprehensive_analysis()
            
            # 增强评分
            enhanced_score, enhanced_signals = EnhancedAnalyzer.calculate_comprehensive_score(hist_data, realtime_data)
            
            # 均线系统评分 ✨ NEW
            ma_score, ma_signals = MAAnalyzer.calculate_ma_score(hist_data)
            
            # 筹码分析评分 ✨ NEW
            chip_score, chip_signals = ChipAnalyzer.calculate_chip_score(hist_data)
            
            # 综合四个评分（加权平均）
            final_score = (score * 0.3 + enhanced_score * 0.3 + ma_score * 0.25 + chip_score * 0.15)
            all_signals = signals + enhanced_signals + ma_signals + chip_signals
            
            recommendation = analyzer.generate_recommendation(final_score)
            
            # 风险分析
            risk_info = RiskAnalyzer.analyze_risk(hist_data)
            
            # 显示分析结果
            display_analysis_result(all_signals, final_score, recommendation, "", risk_info)
            
            # 保存到session_state供导出使用
            st.session_state['analysis_complete'] = True
            st.session_state['last_analysis'] = {
                'stock_code': stock_code,
                'stock_name': stock_name,
                'realtime_data': realtime_data,
                'hist_data': hist_data,
                'signals': signals,
                'score': score,
                'recommendation': recommendation,
                'risk_info': risk_info
            }
            
            st.markdown("---")
            
            # K线图表
            st.subheader("📈 K线图与技术指标")
            display_days = min(len(hist_data), config.CHART_DISPLAY_DAYS)
            chart_data = hist_data.tail(display_days)
            
            fig = create_candlestick_chart(chart_data, stock_name)
            st.plotly_chart(fig, use_container_width=True)
            
            # 数据表格
            with st.expander("📋 查看原始数据"):
                st.dataframe(
                    hist_data.tail(50).sort_values('日期', ascending=False),
                    use_container_width=True
                )
        
        except Exception as e:
            st.error(f"❌ 分析过程中出现错误")
            with st.expander("🔍 查看详细错误信息", expanded=True):
                st.code(traceback.format_exc())


def multi_stock_comparison(stock_codes_input, compare_btn, days):
    """多股票对比分析页面"""
    st.markdown("# 📊 多股票对比分析")
    st.markdown("#### 同时分析多只股票，找出最优标的")
    st.markdown("---")
    
    if not stock_codes_input:
        st.info("👈 请在左侧输入要对比的股票代码（每行一个）")
        
        st.markdown("### 💡 使用示例")
        st.code("""600519
000858
600036
002594""")
        return
    
    if compare_btn:
        # 解析股票代码
        stock_codes = [code.strip() for code in stock_codes_input.split('\n') if code.strip()]
        
        if len(stock_codes) < 2:
            st.warning("⚠️ 请至少输入2只股票进行对比")
            return
        
        st.info(f"🔍 开始对比分析 {len(stock_codes)} 只股票...")
        
        with st.spinner("正在分析中..."):
            try:
                analyzer = MultiStockAnalyzer()
                comparison_df = analyzer.analyze_multiple_stocks(stock_codes, days=days)
                
                if len(comparison_df) == 0:
                    st.error("❌ 没有成功分析的股票")
                    st.warning("可能的原因：")
                    st.markdown("""
                    - 股票代码输入错误（请检查是否为6位数字）
                    - 网络连接问题（无法获取数据）
                    - 股票已退市或停牌
                    - 数据源暂时不可用
                    
                    **建议：**
                    1. 检查股票代码是否正确
                    2. 尝试使用常见股票代码，如：600519、000858、600036
                    3. 查看控制台日志了解详细错误信息
                    """)
                    return
                
                # 检查是否有失败的股票
                failed_stocks = comparison_df[comparison_df['投资建议'].str.contains('分析失败', na=False)]
                if len(failed_stocks) > 0:
                    st.warning(f"⚠️ {len(failed_stocks)} 只股票分析失败")
                    with st.expander("查看失败的股票"):
                        st.dataframe(failed_stocks[['股票代码', '投资建议', '错误详情']], use_container_width=True)
                    # 移除失败的股票
                    comparison_df = comparison_df[~comparison_df['投资建议'].str.contains('分析失败', na=False)]
                
                if len(comparison_df) == 0:
                    st.error("❌ 所有股票都分析失败")
                    return
                
                st.success(f"✅ 成功分析 {len(comparison_df)} 只股票")
                
                # 显示对比表格
                st.subheader("📊 对比结果")
                st.dataframe(comparison_df, use_container_width=True)
                
                # 导出按钮
                if st.button("📥 导出对比结果"):
                    exporter = DataExporter()
                    filepath = exporter.export_multi_stock_comparison(comparison_df)
                    if filepath:
                        st.success(f"✅ 已导出到: {filepath}")
                
                # ===== 可视化对比 =====
                st.markdown("---")
                st.header("📊 多维度对比分析")
                
                # 1. 综合评分对比
                st.subheader("📈 综合评分对比")
                col1, col2 = st.columns([2, 1])
                
                with col1:
                    fig = go.Figure()
                    fig.add_trace(go.Bar(
                        x=comparison_df['股票名称'],
                        y=comparison_df['综合评分'],
                        text=comparison_df['综合评分'].round(2),
                        textposition='auto',
                        marker_color=comparison_df['综合评分'].apply(
                            lambda x: '#26a69a' if x >= 60 else '#ffa726' if x >= 45 else '#ef5350'
                        )
                    ))
                    fig.update_layout(
                        title="股票综合评分对比",
                        xaxis_title="股票",
                        yaxis_title="评分",
                        height=400
                    )
                    st.plotly_chart(fig, use_container_width=True)
                
                with col2:
                    st.markdown("##### 📋 评分说明")
                    st.markdown("""
                    - **≥60分**: 看好 🟢
                    - **45-60分**: 中性 🟡
                    - **<45分**: 看淡 🔴
                    
                    **最高分：** {:.2f}  
                    **最低分：** {:.2f}  
                    **平均分：** {:.2f}
                    """.format(
                        comparison_df['综合评分'].max(),
                        comparison_df['综合评分'].min(),
                        comparison_df['综合评分'].mean()
                    ))
                
                # 2. 交易决策对比
                st.markdown("---")
                st.subheader("💰 交易决策对比")
                
                # 仓位建议分布
                col1, col2 = st.columns(2)
                
                with col1:
                    st.markdown("##### 🎯 仓位建议分布")
                    if '仓位建议' in comparison_df.columns:
                        position_counts = comparison_df['仓位建议'].value_counts()
                        
                        fig = go.Figure(data=[go.Pie(
                            labels=position_counts.index,
                            values=position_counts.values,
                            hole=.3,
                            marker_colors=['#26a69a', '#4ECDC4', '#ffa726', '#ef5350']
                        )])
                        fig.update_layout(
                            title="仓位建议分布",
                            height=350
                        )
                        st.plotly_chart(fig, use_container_width=True)
                
                with col2:
                    st.markdown("##### ⭐ 多周期评级分布")
                    if '多周期评级' in comparison_df.columns:
                        rating_counts = comparison_df['多周期评级'].value_counts()
                        
                        fig = go.Figure(data=[go.Pie(
                            labels=rating_counts.index,
                            values=rating_counts.values,
                            hole=.3,
                            marker_colors=['#26a69a', '#4ECDC4', '#ffa726', '#ef5350', '#9C27B0']
                        )])
                        fig.update_layout(
                            title="多周期评级分布",
                            height=350
                        )
                        st.plotly_chart(fig, use_container_width=True)
                
                # 3. 风险收益对比
                st.markdown("---")
                st.subheader("⚖️ 风险收益对比")
                
                if '风险收益比' in comparison_df.columns and '最新价' in comparison_df.columns:
                    # 提取风险收益比数值（去掉":1"后缀）
                    comparison_df['风险收益比_数值'] = comparison_df['风险收益比'].apply(
                        lambda x: float(str(x).replace(':1', '')) if x != 'N/A' and ':1' in str(x) else 0
                    )
                    
                    fig = go.Figure()
                    
                    # 按风险收益比着色
                    colors = comparison_df['风险收益比_数值'].apply(
                        lambda x: '#26a69a' if x >= 2 else '#ffa726' if x >= 1.5 else '#ef5350'
                    )
                    
                    fig.add_trace(go.Bar(
                        x=comparison_df['股票名称'],
                        y=comparison_df['风险收益比_数值'],
                        text=comparison_df['风险收益比'],
                        textposition='auto',
                        marker_color=colors
                    ))
                    
                    # 添加参考线
                    fig.add_hline(y=2.0, line_dash="dash", line_color="green",
                                 annotation_text="良好(2:1)", annotation_position="right")
                    fig.add_hline(y=1.5, line_dash="dot", line_color="orange",
                                 annotation_text="一般(1.5:1)", annotation_position="right")
                    
                    fig.update_layout(
                        title="风险收益比对比",
                        xaxis_title="股票",
                        yaxis_title="风险收益比",
                        height=400
                    )
                    st.plotly_chart(fig, use_container_width=True)
                    
                    st.info("💡 **风险收益比说明**: ≥2:1为良好，≥1.5:1为一般，<1.5:1不建议操作")
                
                # 4. 买入价格对比
                st.markdown("---")
                st.subheader("💵 建议买入价格对比")
                
                if '稳健买入价' in comparison_df.columns and '最新价' in comparison_df.columns:
                    # 创建价格对比表
                    price_comparison = comparison_df[['股票名称', '最新价', '稳健买入价', '止损价']].copy()
                    
                    # 计算与当前价的差距百分比
                    def calc_diff(row):
                        try:
                            current = float(row['最新价'])
                            buy = float(row['稳健买入价'])
                            if current > 0:
                                return f"{((buy / current - 1) * 100):.2f}%"
                            return 'N/A'
                        except:
                            return 'N/A'
                    
                    price_comparison['买入价差距'] = price_comparison.apply(calc_diff, axis=1)
                    
                    st.dataframe(price_comparison, use_container_width=True)
                    
                    # 价格对比图
                    fig = go.Figure()
                    
                    # 当前价
                    fig.add_trace(go.Scatter(
                        x=comparison_df['股票名称'],
                        y=comparison_df['最新价'].apply(lambda x: float(x) if x != 'N/A' else 0),
                        name='当前价',
                        mode='lines+markers',
                        line=dict(color='#4ECDC4', width=3),
                        marker=dict(size=10)
                    ))
                    
                    # 稳健买入价
                    buy_prices = comparison_df['稳健买入价'].apply(lambda x: float(x) if x != 'N/A' else 0)
                    fig.add_trace(go.Scatter(
                        x=comparison_df['股票名称'],
                        y=buy_prices,
                        name='稳健买入价',
                        mode='lines+markers',
                        line=dict(color='#26a69a', width=2, dash='dash'),
                        marker=dict(size=8)
                    ))
                    
                    # 止损价
                    stop_prices = comparison_df['止损价'].apply(lambda x: float(x) if x != 'N/A' else 0)
                    fig.add_trace(go.Scatter(
                        x=comparison_df['股票名称'],
                        y=stop_prices,
                        name='止损价',
                        mode='lines+markers',
                        line=dict(color='#ef5350', width=2, dash='dot'),
                        marker=dict(size=8)
                    ))
                    
                    fig.update_layout(
                        title="价格关键位对比",
                        xaxis_title="股票",
                        yaxis_title="价格 (¥)",
                        height=400,
                        hovermode='x unified'
                    )
                    st.plotly_chart(fig, use_container_width=True)
                
                # 5. 投资建议汇总
                st.markdown("---")
                st.subheader("📝 投资建议汇总")
                
                # 按仓位建议分组
                if '仓位建议' in comparison_df.columns:
                    st.markdown("##### 🟢 建议加仓的股票")
                    buy_stocks = comparison_df[comparison_df['仓位建议'].str.contains('加仓', na=False)]
                    if len(buy_stocks) > 0:
                        st.dataframe(
                            buy_stocks[['股票名称', '综合评分', '仓位建议', '仓位变化', '多周期评级', '风险收益比']],
                            use_container_width=True
                        )
                    else:
                        st.info("暂无建议加仓的股票")
                    
                    st.markdown("##### 🟡 建议持仓观望的股票")
                    hold_stocks = comparison_df[comparison_df['仓位建议'].str.contains('持仓|观望', na=False)]
                    if len(hold_stocks) > 0:
                        st.dataframe(
                            hold_stocks[['股票名称', '综合评分', '仓位建议', '多周期评级']],
                            use_container_width=True
                        )
                    else:
                        st.info("暂无建议持仓观望的股票")
                    
                    st.markdown("##### 🔴 建议减仓的股票")
                    sell_stocks = comparison_df[comparison_df['仓位建议'].str.contains('减仓', na=False)]
                    if len(sell_stocks) > 0:
                        st.dataframe(
                            sell_stocks[['股票名称', '综合评分', '仓位建议', '仓位变化', '风险收益比']],
                            use_container_width=True
                        )
                    else:
                        st.info("暂无建议减仓的股票")
                
                # 6. 最优选择推荐
                st.markdown("---")
                st.subheader("🏆 最优选择推荐")
                
                # 综合评分最高的前3只
                top_3 = comparison_df.nlargest(3, '综合评分')
                
                col1, col2, col3 = st.columns(3)
                
                for idx, (col, (_, stock)) in enumerate(zip([col1, col2, col3], top_3.iterrows())):
                    with col:
                        rank = ["🥇", "🥈", "🥉"][idx]
                        st.markdown(f"### {rank} {stock['股票名称']}")
                        st.metric("综合评分", f"{stock['综合评分']:.2f}")
                        st.write(f"**投资建议**: {stock['投资建议']}")
                        st.write(f"**仓位建议**: {stock.get('仓位建议', 'N/A')}")
                        st.write(f"**多周期评级**: {stock.get('多周期评级', 'N/A')}")
                        if stock.get('稳健买入价', 'N/A') != 'N/A':
                            st.write(f"**建议买入价**: ¥{stock['稳健买入价']}")
                        if stock.get('风险收益比', 'N/A') != 'N/A':
                            st.write(f"**风险收益比**: {stock['风险收益比']}")
                
            except Exception as e:
                st.error(f"❌ 对比分析失败")
                with st.expander("查看错误详情"):
                    st.code(traceback.format_exc())


def system_config_page():
    """系统配置页面"""
    st.markdown("# ⚙️ 系统配置")
    st.markdown("---")
    
    st.info("🚧 配置功能开发中...")
    
    st.markdown("### 当前配置")
    config_dict = config.to_dict()
    
    # 显示部分重要配置
    important_configs = {
        '数据源': config_dict.get('DATA_SOURCE', 'akshare'),
        '缓存启用': config_dict.get('ENABLE_CACHE', True),
        '请求重试': config_dict.get('REQUEST_RETRY', 3),
        '请求超时': f"{config_dict.get('REQUEST_TIMEOUT', 30)}秒",
        '日志级别': config_dict.get('LOG_LEVEL', 'INFO'),
    }
    
    st.json(important_configs)


def show_welcome_page():
    """显示欢迎页面"""
    # 添加一些空白增加美观度
    st.markdown("<br>", unsafe_allow_html=True)
    
    col1, col2, col3 = st.columns(3)
    
    with col1:
        st.markdown("""
        <div style='background: linear-gradient(135deg, #d1fae5 0%, #a7f3d0 100%); 
                    padding: 30px; 
                    border-radius: 15px; 
                    border: 2px solid #6ee7b7;
                    text-align: center;
                    box-shadow: 0 4px 12px rgba(16, 185, 129, 0.2);'>
            <h3 style='color: #047857; margin-bottom: 15px;'>📈 实时行情</h3>
            <p style='color: #065f46; font-size: 14px;'>获取最新股价、涨跌幅、成交量等</p>
        </div>
        """, unsafe_allow_html=True)
    
    with col2:
        st.markdown("""
        <div style='background: linear-gradient(135deg, #dcfce7 0%, #bbf7d0 100%); 
                    padding: 30px; 
                    border-radius: 15px; 
                    border: 2px solid #86efac;
                    text-align: center;
                    box-shadow: 0 4px 12px rgba(34, 197, 94, 0.2);'>
            <h3 style='color: #15803d; margin-bottom: 15px;'>🎯 量化分析</h3>
            <p style='color: #166534; font-size: 14px;'>多维度技术指标综合评分</p>
        </div>
        """, unsafe_allow_html=True)
    
    with col3:
        st.markdown("""
        <div style='background: linear-gradient(135deg, #fef3c7 0%, #fde68a 100%); 
                    padding: 30px; 
                    border-radius: 15px; 
                    border: 2px solid #fcd34d;
                    text-align: center;
                    box-shadow: 0 4px 12px rgba(234, 179, 8, 0.2);'>
            <h3 style='color: #a16207; margin-bottom: 15px;'>📊 可视化</h3>
            <p style='color: #92400e; font-size: 14px;'>专业K线图表和技术指标</p>
        </div>
        """, unsafe_allow_html=True)
    
    st.markdown("<br><br>", unsafe_allow_html=True)
    st.info("👈 请在左侧选择功能并输入股票信息")


def export_report():
    """导出分析报告"""
    if 'last_analysis' not in st.session_state:
        st.error("❌ 没有可导出的分析结果")
        return
    
    data = st.session_state['last_analysis']
    
    try:
        exporter = DataExporter()
        filepath = exporter.export_analysis_report(
            data['stock_code'],
            data['stock_name'],
            data['realtime_data'],
            data['hist_data'],
            data['signals'],
            data['score'],
            data['recommendation'],
            data['risk_info']
        )
        
        if filepath:
            st.success(f"✅ 分析报告已导出: {filepath}")
        else:
            st.error("❌ 导出失败")
    
    except Exception as e:
        st.error(f"❌ 导出失败: {str(e)}")


if __name__ == "__main__":
    main()

